
import React, { useEffect, useState } from 'react';
import { invoke } from '@tauri-apps/api/core';
import { homeDir, join } from '@tauri-apps/api/path';
import { open } from '@tauri-apps/plugin-dialog';
import {
  FolderOpenOutlined,
  FileOutlined,
  DeleteOutlined,
  EditOutlined,
} from '@ant-design/icons';
import { PageContainer } from '@ant-design/pro-components';
import { Breadcrumb, Button, Dropdown, Input, List, Menu, Modal, Spin, App as AntApp } from 'antd';
import { useAppStore, FileEntry } from '../store';

const FileExplorer = () => {
  const { message, modal } = AntApp.useApp();
  const { currentPath, files, setPath, setFiles, setLoading, isLoading } = useAppStore();
  const [newFolderName, setNewFolderName] = useState('');

  const refreshFileList = async (path: string) => {
    try {
      setLoading(true);
      const fileList = await invoke<FileEntry[]>('list_directory', { path });
      setFiles(fileList);
      setPath(path);
    } catch (error) {
      message.error(`Failed to load directory: ${error}`);
      setLoading(false);
    }
  };

  useEffect(() => {
    homeDir().then(refreshFileList);
  }, []);

  const handleSelectFolder = async () => {
    const selectedPath = await open({ directory: true, multiple: false, defaultPath: await homeDir() });
    if (typeof selectedPath === 'string') await refreshFileList(selectedPath);
  };

  const handleCreateFolder = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!newFolderName) return;
    try {
      const newPath = await join(currentPath, newFolderName);
      await invoke('create_folder', { path: newPath });
      setNewFolderName('');
      await refreshFileList(currentPath);
      message.success(`Folder '${newFolderName}' created.`);
    } catch (error) {
      message.error(`Failed to create folder: ${error}`);
    }
  };

  const handleItemClick = async (file: FileEntry) => {
    if (file.is_dir) {
      const newPath = await join(currentPath, file.name);
      await refreshFileList(newPath);
    }
  };

  const handleDeleteItem = (item: FileEntry) => {
    modal.confirm({
      title: `Delete '${item.name}'?`,
      content: `Are you sure you want to delete this ${item.is_dir ? 'directory' : 'file'}? This action cannot be undone.`,
      okText: 'Delete',
      okType: 'danger',
      onOk: async () => {
        try {
          const path = await join(currentPath, item.name);
          await invoke('delete_item', { path });
          await refreshFileList(currentPath);
          message.success(`'${item.name}' deleted.`);
        } catch (error) {
          message.error(`Failed to delete: ${error}`);
        }
      },
    });
  };

  const handleRenameItem = (item: FileEntry) => {
    let newName = item.name;
    modal.confirm({
      title: `Rename '${item.name}'`,
      content: <Input defaultValue={item.name} onChange={(e) => newName = e.target.value} />,
      onOk: async () => {
        try {
          const oldPath = await join(currentPath, item.name);
          const newPath = await join(currentPath, newName);
          await invoke('rename_item', { oldPath, newPath });
          await refreshFileList(currentPath);
          message.success(`Renamed to '${newName}'.`);
        } catch (error) {
          message.error(`Failed to rename: ${error}`);
        }
      },
    });
  };

  const breadcrumbItems = currentPath.split('/').filter(Boolean).map((part, index, arr) => {
    const path = '/' + arr.slice(0, index + 1).join('/');
    return { title: part, onClick: () => refreshFileList(path) };
  });

  const renderItemMenu = (item: FileEntry) => (
    <Menu>
      <Menu.Item key="rename" icon={<EditOutlined />} onClick={(e) => { e.domEvent.stopPropagation(); handleRenameItem(item); }}>Rename</Menu.Item>
      <Menu.Item key="delete" icon={<DeleteOutlined />} danger onClick={(e) => { e.domEvent.stopPropagation(); handleDeleteItem(item); }}>Delete</Menu.Item>
    </Menu>
  );

  return (
    <PageContainer
      header={{
        title: 'File Explorer',
        breadcrumb: { items: breadcrumbItems },
        extra: [<Button key="select" type="primary" onClick={handleSelectFolder}>Select Folder</Button>]
      }}
    >
      <div style={{ padding: '24px', background: '#fff' }}>
        <form onSubmit={handleCreateFolder} style={{ marginBottom: '20px', display: 'flex', gap: '8px' }}>
          <Input value={newFolderName} onChange={(e) => setNewFolderName(e.target.value)} placeholder="New folder name..." />
          <Button type="default" htmlType="submit">Create Folder</Button>
        </form>
        <Spin spinning={isLoading}>
          <List
            itemLayout="horizontal"
            dataSource={files}
            renderItem={(item) => (
              <Dropdown overlay={renderItemMenu(item)} trigger={['contextMenu']}>
                <List.Item onClick={() => handleItemClick(item)} style={{ cursor: item.is_dir ? 'pointer' : 'default' }}>
                  <List.Item.Meta avatar={item.is_dir ? <FolderOpenOutlined /> : <FileOutlined />} title={<a>{item.name}</a>} description={`Size: ${item.size} bytes`} />
                </List.Item>
              </Dropdown>
            )}
          />
        </Spin>
      </div>
    </PageContainer>
  );
};

export default FileExplorer;
